import store from '@/store'
import {
	passwordFreeLogin
} from '@/common/js/userLogin.js'

let isRefreshing = true;
let queue = [];
// 重新调用请求
function onRecall() {
	// console.log('当前的queue', queue)
	queue.length && queue.forEach((callback) => {
		// console.log('当前的callback', callback)
		callback();
	})
	queue = [];
}
// 缓存请求
function cacheQueue(callback) {
	queue.push(callback)
}

const ajax = (opt) => {
	const newOpt = opt || {}
	newOpt.url = opt.url || '';
	newOpt.data = opt.data || null;
	newOpt.method = opt.method || 'POST';
	newOpt.header = {
		// "content-type":"application/json"
		"token": store.state.token,
		"content-type": opt.header || "application/x-www-form-urlencoded"
	};
	
	// #ifdef H5
	let url = process.env.NODE_ENV == 'development' ? (store.state.proxyUrl + newOpt.url) : newOpt.url
	// #endif
	
	// #ifndef H5
	let url = (store.state.proxyUrl + newOpt.url)
	// #endif

	// console.log("当前的url", url)

	let promise = new Promise(function(resolve, reject) {
		uni.request({
			method: newOpt.method,
			url: url,
			header: newOpt.header,
			data: {
				tenantId: store.state.tenantId,
				...newOpt.data
			},
			dataType: 'json',
			callback: opt.callback || ''
		}).then(
			(data) => {
				var [error, res] = data;
				// callback token过期后重新请求接口，接口返回的数据
				if (opt.callback && res && res.data) return opt.callback(res.data);
				if (res && res.data && res.data.code == 8200) {
					resolve(res.data)
				} else if (res && res.data && res.data.code == 8302) {
					// 将需要重新执行的接口缓存到一个队列中
					cacheQueue(() => {
						ajax({
							...opt,
							callback: resolve
						})
					})

					if (isRefreshing) {
						passwordFreeLogin().then((res) => {
							console.log('========重新登陆返回的token========', res)
							// 依次去执行缓存的接口
							onRecall();
							isRefreshing = true;
						})
					}
					isRefreshing = false;
					// reject(res)
				} else {
					console.log('错误信息0', res, error)
					if(res && res.data) {
            reject(res.data)
						setTimeout(() => {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							});
						})
					} else {
						console.log('请求错误', error)
            reject(error)
						// uni.showToast({
						// 	title: error.errMsg,
						// 	icon: 'none'
						// });
					}
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
}
export default ajax
